package org.mijia.dotsbox.core.search;

import java.util.concurrent.atomic.AtomicInteger;

public abstract class ReferCounter<Type> {

	protected final Type resource;
    protected final AtomicInteger referenceCount = new AtomicInteger(0);
    
    
    public ReferCounter(Type ref) {
        resource = ref;
    }
    
    public final ReferCounter<Type> incre() {
        int ref = referenceCount.incrementAndGet();
        return this;
    }
    
    public final Type get() {
        return resource;
    }
    
    protected abstract void close() throws Exception;
    
    public synchronized void decre() throws Exception {
        int ref = referenceCount.decrementAndGet();
        if (ref == 0) {
            close();
        }
    }
}
